package com.kinyx.framework.db.sentence.res;

import javax.persistence.Entity;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

import com.kinyx.framework.enums.impl.ErrorCodeX;
import com.kinyx.framework.exception.KRuntimeException;

public class Res {

	public static Table of(final Class<?> clazz) {
		final StaticMetamodel annotation = clazz.getAnnotation(StaticMetamodel.class);
		if (annotation != null) {// 资源文件，实体类为注解值。
			final Class<?> entityClass = annotation.value();
			if (entityClass.getAnnotation(Entity.class) != null) {
				return new Table(entityClass);
			}
		}
		// 当前类为实体类
		if (clazz.getAnnotation(Entity.class) != null) { return new Table(clazz); }
		throw new KRuntimeException(ErrorCodeX.NotConfiged);
	}

	public static Column toCol(final SingularAttribute<?, ?> attr) {
		return new Column(attr.getDeclaringType().getJavaType(), attr.getName());
	}

	public static Column[] toCols(final SingularAttribute<?, ?>[] attrs) {
		if (attrs == null) { return null; }
		final Column[] columns = new Column[attrs.length];
		for (int i = 0; i < attrs.length; i++) {
			columns[i] = toCol(attrs[i]);
		}
		return columns;
	}

}
